package org.example.redishello1.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.example.redishello1.entity.Product;
import org.example.redishello1.mapper.ProductMapper;
import org.example.redishello1.service.ProductService;
import org.example.redishello1.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * (Product)表服务实现类
 *
 * @author 全哥哥
 * @since 2025-10-20 16:50:29
 */
@Service("productService")
public class ProductServiceImpl implements ProductService {
    @Resource
    private ProductMapper productMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public R selectById(Long id) {
        ValueOperations forValue = redisTemplate.opsForValue();
        Object o = forValue.get(id);
        Product product = null;
        if (o==null){
            product = (Product) productMapper.selectById(id);
            if (product ==null){
                //redis和mysql数据库中都没有该对象,为了防止缓存穿透,创建error对象,存在三分钟,在这三分钟内无法访问mysql数据库
                forValue.set("p:"+id,"error", Duration.between(LocalDateTime.now(),LocalDateTime.now().plusMinutes(3)));//redis中纯数字作为key容易出错
            }else{
                //说明查到了,转json,存5分钟
                forValue.set("p:"+id, JSONObject.toJSONString(product),5, TimeUnit.MINUTES);
            }
        }else {
            //redis查到了
            if (!"error".equals(o)){
                 product = JSONObject.parseObject(o.toString(), Product.class);
            }
        }
        return R.success(product);

    }
}
